package org.example.springtest.config;

import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.springtest.model.dto.responseMessage;
import org.example.springtest.model.dto.user.LoginResponse;
import org.example.springtest.service.RedisService;
import org.example.springtest.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private RedisService redisService;
    private final JwtProperties jwtProperties;

    public Boolean isWhitePath(String path) {
        List<String> whiteList = jwtProperties.getWhitelist();
        return whiteList.stream().anyMatch(i -> i.equals(path));
    }

    public JwtAuthenticationFilter(JwtUtil jwtUtil, JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        String authHeader = request.getHeader("Authorization");
        String path = request.getRequestURI();
        boolean isWhite = isWhitePath(path);
        if (!isWhite) {
            if (Objects.isNull(authHeader)) {
                response.getWriter().write(objectMapper.writeValueAsString(responseMessage.error(401, "请先登录")));
                return;
            } else {
                var isBearer = authHeader.startsWith("Bearer ");
                var token = authHeader.substring(7);
                var userId = JwtUtil.validateTokenAndGetUsername(token);
                if (userId==null||!isBearer) {
                    String json = objectMapper.writeValueAsString(responseMessage.error(401, "非法签名"));
                    response.getWriter().write(json);
                    return;
                }
                Map redisUser =   redisService.get("user:" + userId);
                if(!token.equals(redisUser.get("token"))){
                    String json = objectMapper.writeValueAsString(responseMessage.error(401, "登录已过期,请重新登录"));
                    response.getWriter().write(json);

                    return;
                }
                request.setAttribute("userId", userId);
            }
        }
        filterChain.doFilter(request, response);
    }
}
